/*
https://leetcode-cn.com/problems/bus-routes/solution/gong-jiao-lu-xian-by-leetcode-solution-yifz/
 */
import java.util.*;

public class Solution815 {
    public int numBusesToDestination(int[][] routes, int source, int target) {
        if (source==target){
            return 0;
        }
        Map<Integer,List<Integer>> map=new HashMap<>();
        int[][] reach=new int[routes.length][routes.length];
        for (int i=0;i<routes.length;i++){
            for (int i1 : routes[i]) {
                List<Integer> l=map.getOrDefault(i1,new ArrayList<>());
                for (Integer integer : l) {
                    reach[i][integer]=reach[integer][i]=1;
                }
                l.add(i);
                map.put(i1,l);
            }
        }
        Map<Integer,Integer> visit=new HashMap<>();
        Queue<int[]> queue=new LinkedList<>();
        List<Integer> list=map.getOrDefault(source,new ArrayList<>());
        for (Integer integer : list) {
            queue.offer(new int[]{integer,1});
            visit.put(integer,1);
        }
        while (!queue.isEmpty()){
            int[] ints=queue.poll();
            for (int i=0;i<routes.length;i++){
                if (reach[ints[0]][i]==1 && visit.getOrDefault(i,Integer.MAX_VALUE)>ints[1]+1){
                    queue.offer(new int[]{i,ints[1]+1});
                    visit.put(i,ints[1]+1);
                }
            }
        }
        int min=Integer.MAX_VALUE;
        list=map.getOrDefault(target,new ArrayList<>());
        for (Integer integer : list) {
            min=Math.min(min,visit.getOrDefault(integer,Integer.MAX_VALUE));
        }
        return min==Integer.MAX_VALUE?-1:min;
    }

    public static void main(String[] args) {
        System.out.println(new Solution815().numBusesToDestination(new int[][]{{1,2,7},{3,6,7}},1,6));
    }
}
